import { component$, useSignal, $ } from "@builder.io/qwik";

export const App = component$(() => {
  const count = useSignal(50000);
  const show = useSignal(true);
  const time = useSignal(0);
  const color = useSignal("red");

  // 切换显示
  const onToggle = $(() => {
    show.value = !show.value;
    if (!show.value) return;
    const key = "box_" + (count.value - 1);
    let timer: any;
    const t = Date.now();
    timer = setInterval(() => {
      if (document.getElementById(key)) {
        time.value = Date.now() - t;
        clearInterval(timer);
      }
    });
  });

  // change background color
  const onBg = $((c: string) => {
    color.value = c;
    const dom = document.getElementById(
      "box_" + (count.value - 1)
    ) as HTMLElement;
    let timer: any;
    if (!dom) return;
    const t = Date.now();
    timer = setInterval(() => {
      if (dom.style.backgroundColor === c) {
        time.value = Date.now() - t;
        clearInterval(timer);
      }
    });
  });

  return (
    <>
      显示：{show} len: {count} time: {time}
      <br />
      <button onClick$={() => onToggle()}>显示/切换</button>
      &nbsp;&nbsp;
      <button onClick$={() => onBg("red")}>红色</button>
      &nbsp;&nbsp;
      <button onClick$={() => onBg("green")}>绿色</button>
      <hr />
      <div style={{ overflow: "auto", maxHeight: "90vh" }}>
        {show.value &&
          Array.from({ length: count.value }).map((_, i) => (
            <span
              key={i}
              id={"box_" + i}
              style={{
                width: "20px",
                height: "20px",
                marginRight: "5px",
                marginBottom: "5px",
                display: "inline-block",
                cursor: "pointer",
                backgroundColor: color.value,
              }}
            />
          ))}
      </div>
    </>
  );
});
